package cn.bjc.controller;

import cn.bjc.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {
    
    @Autowired
    private RestTemplate restTemplate;
    

    @GetMapping("/getById/{id}")
    //开启该接口的熔断功能,标记方法熔断，并指定降级方法
    @HystrixCommand(fallbackMethod = "getByIdFallback") 
    public User getById(@PathVariable("id") Long id){
        //旧方法:发送http请求,使用http工具类,但是这里不用
        //新方法:使用RestTemplate发送请求
        
        //定义路径
        //String url = "http://localhost:10020/user/getById/" + id;
        //导入负载均衡后,拿到此服务的应用名称,就相当于拿到了这个服务的集群的所有ip和端口号
        String url = "http://user-server/user/getById/" + id;
        User forObject = restTemplate.getForObject(url, User.class);

        return forObject;
    }

    //该方法为降级方法，参数和返回值必须和被熔断的方法一致 ，方法名要和fallbackMethod的值一致
    public User getByIdFallback(@PathVariable("id") Long id){
        //
        return new User(-1L, "服务熔断触发", "该服务不可用！");
    }
    
    

}